<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
//class User extends MY_Controller {
    private $ERROR_DB = false;
    
    public function __construct() {
        parent::__construct();
        
        $this->load->helper('form');
        $this->load->model('role_model');
        $this->load->model('setting_model'); // нужно для инициализации настроек до входа пользователя
        if($this->db->db_connect() === false) $this->ERROR_DB = true;
    }

    public function index(){
        redirect('');
    }
    
    /**
     * User custom style
     */
    public function custom_css(){
        header('Content-type: text/css');
        $this->load->model('setting_model');
        $style = "/* custom style generated */\n";
        try{
            $style .= sprintf("body { background-color: %s; }\n", $this->setting_model->get_body_color());
        }catch(Exception $e){
            $style = "";
            log_message('error', $e->getMessage());
        }
        echo $style;
    }
    
    public function auth(){
        header('HTTP/1.0 401 Unauthorized');
        $data = array();
//        $data['title'] = "Авторизация пользователя";

        $refer = isset($_GET['refer'])?urldecode(filter_input(INPUT_GET, 'refer')):"";
        
        if(stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE')){
            $data['error'] = 'Internet Explorer не поддерживается системой в полной мере. Рекомендуем сменить браузер!';
        }

        if(isset ($_POST['btnlogin']) && !empty($_POST['login'])){
            
            $log_ary = $this->prep_login_user($_POST['login']);
            @$query = @$this->db->query("select * from users where user_name = ? ",array($log_ary['login']));
            
            if($query->num_rows() > 0){
                $row = $query->row_array();

                if(@$row['DOMAIN'] == 'from_file' || empty($row['DOMAIN'])){
                    if($this->login_via_files($log_ary['login'], $_POST['password'],$log_ary['sub_login'])){
                        redirect($refer);
                        exit();
                    }
                }else{
                    if($this->logining($log_ary['login'], $_POST['password'], $row['DOMAIN'],$log_ary['sub_login'])){
                        redirect($refer);
                        exit();
                    }
                }
            }

            if($this->ERROR_DB){
                $data['error'] = 'Нет подключения к базе данных!';
            }else{
                $data['error'] = 'Неверное имя пользователя или пароль!';
            }
        }
//        $data['content_view'] = 'auth_form';
        
        $this->load->view('ver2/signin_view',$data);
    }
    
    public function logout(){
        $this->session->sess_destroy();
        $this->load->view('ver2/bye_view');
    }
    
    private function logining($user_name,$password,$domain,$sub_user=FALSE){
        
        if($this->ERROR_DB){
            return FALSE;
        }else{
            
            $user_name = replace_quotes($user_name);
            $domain = replace_quotes($domain);

            //запуск хранимой функции
            $conn = $this->db->db_connect();
            $s = @OCIParse($conn,"SELECT common.auth_ad(:user_name,:user_pass,:domain) as auth_result from dual");
            OCIBindByName($s,":user_name", $user_name);
            OCIBindByName($s,":user_pass", $password);
            OCIBindByName($s,":domain", $domain);
            OCIExecute($s, OCI_DEFAULT);

            OCIFetch($s);

            $result = ociresult($s, "AUTH_RESULT");

            if($result == $user_name){
                //проверка на доступ к сайту
                $u_query = $this->db->query("select * from users, roles_users where id = user_id and user_name = ? ", array(strtolower(replace_quotes($user_name))));
                if ($u_query->num_rows() > 0){
                    $row = $u_query->first_row('array');
                    
                    if(($sub_user !== FALSE) && ($row['ROLE_ID'] == 2)){
                        $subu_query = $this->db->query("select * from users, roles_users where id = user_id and user_name = ? ", array($sub_user));
                        if($subu_query->num_rows() > 0){
                            unset($row);
                            $row = $subu_query->first_row('array');
                        }else{
                            return FALSE;
                        }
                    }
                    
                    $u_role     = $row['ROLE_ID'];
                    $u_id       = $row['USER_ID'];
                    $u_logins   = $row['LOGINS'];
                    $u_name     = $row['USER_NAME'];
                    
                    $role_query = $this->db->query("select to_char(START_DATE_ALLOW,'YYYY-MM-DD') as START_DATE, to_char(END_DATE_ALLOW,'YYYY-MM-DD') as END_DATE from roles where id = ? ", array($u_role));
                    $role_row = $role_query->row_array();
                    
                    $user_data = array('login'=>$u_name,'logged_in'=>TRUE,'role'=>$u_role,'uid'=>$u_id, 'start_date' =>  $role_row['START_DATE'], 'end_date' => $role_row['END_DATE']);//
                    $this->session->set_userdata($user_data);
                    $this->db->query("UPDATE users SET logins=?, last_login=sysdate WHERE id=?",array($u_logins+1,$u_id));
                    return TRUE;
                }else{
                    return FALSE;
                }
            }else{
                return FALSE;
            }
            OCILogoff($conn);
        }
    }

    private function login_via_files($user_name,$password,$sub_user=FALSE){

        $data = file($this->config->item('path_users_dat'));
        $user_name = replace_quotes($user_name);
        
        foreach ($data as $value) {
            if(trim($value) == trim($user_name.":".md5($password))){
                
                //проверка на доступ к сайту
                $u_query = $this->db->query("select * from users, roles_users where id = user_id and user_name = ? ", array($user_name));
                if ($u_query->num_rows() > 0){
                    $row = $u_query->first_row('array');
                    
                    //if(($sub_user !== FALSE) && ($row['ROLE_ID'] == $this->config->item('admin_role_id'))){
                    if(($sub_user !== FALSE) && $this->role_model->isAdminRole($row['ROLE_ID']) ){
                        $subu_query = $this->db->query("select * from users, roles_users where id = user_id and user_name = ? ", array($sub_user));
                        if($subu_query->num_rows() > 0){
                            unset($row);
                            $row = $subu_query->first_row('array');
                        }else{
                            return FALSE;
                        }
                    }
                    
                    $u_role     = $row['ROLE_ID'];
                    $u_id       = $row['USER_ID'];
                    $u_logins   = $row['LOGINS'];
                    $u_name     = $row['USER_NAME'];

                    $role_query = $this->db->query("select to_char(START_DATE_ALLOW,'YYYY-MM-DD') as START_DATE, to_char(END_DATE_ALLOW,'YYYY-MM-DD') as END_DATE from roles where id = ? ", array($u_role));
                    $role_row = $role_query->row_array();
                    
                    $user_data = array('login'=>$u_name,'logged_in'=>TRUE,'role'=>$u_role,'uid'=>$u_id, 'start_date' =>  $role_row['START_DATE'], 'end_date' => $role_row['END_DATE']);//
                    $this->session->set_userdata($user_data);
                    $this->db->query("UPDATE users SET logins=?, last_login=sysdate WHERE id=?",array($u_logins+1,$u_id));
                    return TRUE;
                }else{
                    return FALSE;
                }
                exit ();
            }
        }
        return FALSE;
    }
    
    private function prep_login_user($login){
        $res = array();
        $sub_log_ary = preg_split("#[/\\\|]#", $login, 2);
        
        $res['login'] = trim(strtolower(replace_quotes($sub_log_ary['0'])));
        if(count($sub_log_ary) > 1){
            $res['sub_login'] = trim(strtolower(replace_quotes($sub_log_ary['1'])));
        }else{
            $res['sub_login'] = FALSE;
        }
        return $res;
    }
    
}
